package com.qumitech.visualnovel.component.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.protocol.HTTP;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by fangzhipeng on 2017/10/27
 */
public class UrlUtils {

    private static final String CHARSET = "UTF-8";

    // 将request中的参数转换成Map
    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

    // 将request中的参数转换成Map
    public static Map<String, String> convertRequestBodyToMap(HttpServletRequest request) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            String reqBody = URLDecoder.decode(sb.toString(), HTTP.UTF_8);
            Map<String, String> itemMap = JSONObject.parseObject(reqBody, new TypeReference<Map<String, String>>() {});
            return itemMap;
        } catch (Exception e) {
            return null;
        }

    }

    public static Map<String, String> parse(String params) {
        if (StringUtils.isEmpty(params)) {
            return null;
        }
        try {
            Map<String, String> map = new HashMap<>();
            String[] paramAr = params.split("&");
            for (String param : paramAr) {
                String[] keyValue = param.split("=");
                String key = URLDecoder.decode(keyValue[0], CHARSET);
                String value = URLDecoder.decode(keyValue[1], CHARSET);
                map.put(key, value);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String genParams(Map<String, String> params) {
        if (params == null || params.entrySet().size() == 0) {
            return null;
        }
        try {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = URLEncoder.encode(entry.getKey(), CHARSET);
                String value = URLEncoder.encode(entry.getValue(), CHARSET);
                sb.append("&").append(key).append("=").append(value);
            }
            return sb.substring(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("coins", "111");
        params.put("哈哈哈哈", "=呵呵呵");
        String genParams = genParams(params);
        System.out.println(genParams);
        params = parse(genParams);
        System.out.println("hit");
    }

    public static String taobaoGetIPAddr(HttpServletRequest request) {

        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=%s";
        String res = HttpInvokeUtil.httpGetWithHeader(String.format(url, request.getRemoteAddr()), null, null);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject != null) {
            String data = jsonObject.getString("data");
            System.out.println(data);
        }
        return "127.0.0.1";
    }

    /**
     * APISTORE_GET
     * @param strUrl
     * @param param
     * @param appcode
     * @return
     */
    public static String APISTORE(String strUrl, String param, String appcode, String Method) {

        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;
        try {
            url = new URL(strUrl + "?" + param);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod(Method);
            httpURLConnection.setUseCaches(false); // 不用缓存
            httpURLConnection.connect();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }

    /**
     * APISTORE_GET 银行卡认证
     * @param strUrl
     * @param param
     * @param appcode
     * @return
     */
    public static String APISTORE_GET(String strUrl, String param, String appcode) {

        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;
        try {
            url = new URL(strUrl + "?" + param);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Authorization", "APPCODE " + appcode);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET"); // get方式
            httpURLConnection.setUseCaches(false); // 不用缓存
            httpURLConnection.connect();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }
}
